package com.ttxz.sample.view.widget

import android.content.Context
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.SeekBar
import androidx.appcompat.app.AlertDialog
import com.hjq.toast.ToastUtils
import com.ttxz.sample.databinding.DialogVolumeSettingBinding

class VolumeSettingDialog(context: Context) : AlertDialog(context) {
    lateinit var binding:DialogVolumeSettingBinding
    lateinit var mAudioManager:AudioManager

    var nowVolume = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mAudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager

        binding = DialogVolumeSettingBinding.inflate(LayoutInflater.from(context), null, false)
        setContentView(binding.root)

        binding.tvVolumeStr.text = "当前音量：${getCurrentVolume100()}"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            binding.seekBar.setProgress(getCurrentVolume100(), false)
        }else{
            binding.seekBar.progress = getCurrentVolume100()
        }
        Log.e("@@@", "最大音量：${mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)}")

        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                Log.e("@@@", "[onProgressChanged], progresss:$progress ---- fromUser:$fromUser")
                binding.tvVolumeStr.text = "当前音量：$progress"
                nowVolume = progress
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })
        binding.btnSetOk.setOnClickListener {
            val nowVolumeTemp = getSetVolume()
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, nowVolumeTemp,
                AudioManager.FLAG_PLAY_SOUND
            )
            ToastUtils.show("$nowVolume 音量设置成功:${nowVolumeTemp}")
            dismiss()
        }

    }

    /**
     * 获取100基数的当前设置音量
     */
    fun getCurrentVolume100():Int{
        return (100 * (mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toDouble())).toInt()
    }

    /**
     * 将最大100的音量转换为系统中的合适音量，用于设置到系统中
     */
    fun getSetVolume():Int{
        return ((nowVolume / 100.toDouble()) * mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)).toInt()
    }
}